﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using DG.Tweening;

public class UINode : UICompontent ,IPointerEnterHandler, IPointerExitHandler
{
	private GridData data;
	private bool locked = false;
	public bool isSeed = false;
	private UINode parentNode = null;

	private UIEffect node;
	private List<UIEffect> uiGuideEffectList = new List<UIEffect>();
	private List<UIEffect> uiEffectList = new List<UIEffect>();

	private Button btn = null;
	private UIEffect buttonMask = null;

	public int keyX = 0;
	public int keyY = 0;

	public GridType cacheLastType;


	public void bindData(GridData gridData)
	{
		data = gridData;
	}

	void Start () 
	{
		btn = gameObject.GetComponent<Button> ();
		btn.onClick.AddListener(OnTouch);

		creatSkin ();
		UIEvent.getInstance ().AddTouchOtherNoteListener (this.cancleTouch);
		UIEvent.getInstance ().AddNodeRefreshListener (this.refresh);
	}
		
	void creatSkin()
	{
		Image img = gameObject.GetComponent<Image> ();
		var dirtName = img.sprite.name;

		cacheLastType = data.Type;
//		EnumConvert.GetGridTypeValue(data.Type);
		switch(data.Type)
		{
			case GridType.Air:
//				img.color = new Color(0,0,1,0.5f);
				break;
			case GridType.DirtBest:
				img.sprite = Resources.Load ("dirt5", typeof(Sprite)) as Sprite;
				break;
			case GridType.DirtHigh:
				img.sprite = Resources.Load ("dirt4", typeof(Sprite)) as Sprite;
				break;
			case GridType.DirtMiddle:
				img.sprite = Resources.Load ("dirt3", typeof(Sprite)) as Sprite;
				break;
			case GridType.DirtLower:
				img.sprite = Resources.Load ("dirt2", typeof(Sprite)) as Sprite;
				break;
			case GridType.DirtLowest:
				img.sprite = Resources.Load ("dirt1", typeof(Sprite)) as Sprite;
				break;
			default:
				Debug.LogError ("UNKNOW:GridType");
				break;
		}

		if(data.IsTarget)
			img.sprite = Resources.Load ("target", typeof(Sprite)) as Sprite;

		if (data.TreePart != null && data.TreePart.Type == TreePartType.Node) {
			TreeNodeData treeNodeData = (TreeNodeData)data.TreePart;
			if (!treeNodeData.IsLeaf && uiEffectList != null) {
				for (var i = 0; i < uiEffectList.Count; i++) {
					Destroy (uiEffectList [i].gameObject);
					uiEffectList.Remove (uiEffectList [i--]);
				}
			}
		}
		if (uiEffectList.Count >= 2) {
			for (var i = 0; i < uiEffectList.Count; i++) {
				if ((!uiEffectList [i].isLeaf && !uiEffectList[i].isRoot) || uiEffectList[i].isSeed)
					continue;
				Destroy (uiEffectList [i].gameObject);
				uiEffectList.Remove (uiEffectList [i--]);
			}
		}
	}

	void refresh()
	{
		if (this.uiEffectList.Count > 0) {
			if (data.TreePart.Type == TreePartType.Node) {
				TreeNodeData treeNodeData = (TreeNodeData)data.TreePart;
				if (treeNodeData.IsLeaf && node.isLeaf) {
					var num = treeNodeData.GetValue ();
					playOutputAnim ((float)num);
				}
			} else {
				var num = (int)EnumConvert.GetGridTypeValue (cacheLastType);
				playOutputAnim ((float)num);
			}
		}
		creatSkin ();
	}

	void Update () 
	{
		
	}

	void OnTouch()
	{
		if (this.parentNode != null) 
		{
			var temp = parentNode;
			parentNode.cancleTouch ();
			selectReady (parentNode);	
			return;
		}
		if(!locked)
			UIEvent.getInstance().touchOtherEvent.Invoke ();
		//如果没有被锁定过，点击将会展示先一步操作的指引
		if (!locked) 
		{
			locked = true;
			showGuide ();
			return;
		}
		if (isSeed)
			return;
	}

	void cancleTouch()
	{
		locked = false;
		removeGuide ();
	}

	UIEffect creatNodeGuide(string path = "node")
	{
		UIDialog parent;
		if (path == "line" || path == "sinLine")
			parent = transform.parent.GetComponent<UIScene>();
		else
			parent = this;
		node = UIManager.getInstance ().addEffectByPath (path, parent, 30, 30, path == "line" || path == "sinLine");
		uiGuideEffectList.Add (node);
		return node;
	}

	UIEffect creatResultLine(string path = "node")
	{
		UIDialog parent;
		if (path == "line" || path == "sinLine")
			parent = transform.parent.GetComponent<UIScene>();
		else
			parent = this;
		node = UIManager.getInstance ().addEffectByPath (path, parent, 30, 30, path == "line" || path == "sinLine");
		uiEffectList.Add (node);
		return node;
	}

	void creatNodeGuideTween(UINode uiNode,bool isGuide = true)
	{
		var distanceX = uiNode.getRectTransform ().position.x - getRectTransform ().position.x;
		var distanceY = uiNode.getRectTransform ().position.y - getRectTransform ().position.y;
		UIEffect uiEffect;
		if (isGuide) {
			if (distanceX == 0 || distanceY == 0) {
				uiEffect = creatNodeGuide ("line");
				uiEffect.setSize (16, 64);
				uiEffect.setPostion (0+this.getRectTransform().localPosition.x,this.getRectTransform().localPosition.y-8);
			} else {
				uiEffect = creatNodeGuide ("sinLine");
				uiEffect.setSize (32, 64);
				uiEffect.setPostion (0+this.getRectTransform().localPosition.x,this.getRectTransform().localPosition.y);
			}
		} else {
			if (distanceX == 0 || distanceY == 0) {
				uiEffect = creatResultLine ("line");
				uiEffect.setSize (16, 64);
//				uiEffect.setPostion (0,-8);
				uiEffect.setPostion (0+this.getRectTransform().localPosition.x,this.getRectTransform().localPosition.y-8);
			} else {
				uiEffect = creatResultLine ("sinLine");
				uiEffect.setSize (32, 64);
				uiEffect.setPostion (0+this.getRectTransform().localPosition.x,this.getRectTransform().localPosition.y-8);
			}
		}

		Vector3 vector = new Vector3();
		if (distanceY > 0) {
			if (distanceX < 0) {
				uiEffect.setPostion (this.getRectTransform().localPosition.x,+this.getRectTransform().localPosition.y-32);
			} else if (distanceX > 0) {
				uiEffect.setPostion (64+this.getRectTransform().localPosition.x,this.getRectTransform().localPosition.y-32);
				uiEffect.getRectTransform ().localScale = new Vector3(-1,1,1);
			}
		}
		else if (distanceY == 0) {
			if (distanceX > 0) {
				uiEffect.setPostion (32+this.getRectTransform().localPosition.x,8+this.getRectTransform().localPosition.y-32);
				uiEffect.getRectTransform().localEulerAngles = new Vector3 (0,0,-90);
			}
			else if (distanceX < 0) {
				uiEffect.setPostion (32+this.getRectTransform().localPosition.x,this.getRectTransform().localPosition.y-8-32);
				uiEffect.getRectTransform().localEulerAngles = new Vector3 (0,0,90);
			}
		}
		else if (distanceY < 0) {
			if (distanceX < 0) {
				uiEffect.setPostion (32+this.getRectTransform().localPosition.x,this.getRectTransform().localPosition.y-96);
				uiEffect.getRectTransform ().localScale = new Vector3(-1,1,1);
			} else if (distanceX > 0) {
				uiEffect.setPostion (32+this.getRectTransform().localPosition.x,this.getRectTransform().localPosition.y-96);
				uiEffect.getRectTransform ().localScale = new Vector3(1,1,1);
			}
		}
//		uiEffect.getRectTransform ().localEulerAngles = vector;
	}

	UIEffect creatNodeResult()
	{
		UIEvent.getInstance().nodeRefreshEvent.Invoke ();

		if (data.Type == GridType.Air) {
			node = UIManager.getInstance ().addEffectByPath ("leaf", this, 96, 96);
			node.setPostion (-48, -48);
		} 
		else if (data.CanSeed) {
			node = UIManager.getInstance ().addEffectByPath ("seed", this, 64, 64);
			node.setPostion (-32,-32);
		}
		else {
			node = UIManager.getInstance ().addEffectByPath ("seed", this, 64, 64);
			node.setPostion (-32,-32);
			node.setSize (0, 0);
		}

		uiEffectList.Add (node);
		return node;
	}

	void removeGuide()
	{
		this.parentNode = null;
		for (var i = 0; i < uiGuideEffectList.Count; i++) 
		{
			Destroy (uiGuideEffectList[i].gameObject);
			uiGuideEffectList.Remove (uiGuideEffectList[i--]);
		}
	}
		
	void showGuide()
	{
		if(data.CanSeed)
		{
			isSeed = true;
			var uiEffect = creatNodeResult ();
			uiEffect.isSeed = true;
			locked = false;
			PlayerData.Instance.SetSeed (data);
			return;
		}
		else if (data.TreePart == null) 
		{
			locked = false;
			return;
		}
			
		var uiNodeList = UIScenenManager.getInstance().GetCanGrowUpList (data.TreePart);
		if (uiNodeList != null) 
		{
			foreach (UINode uiNode in uiNodeList) 
			{
				uiNode.parentNode = this;
				creatNodeGuideTween (uiNode);
			}
		}
	}

	void selectReady(UINode parentN = null)
	{
		//资源不足
		GrowUpRes growUpRes = PlayerData.Instance.GetResCost(data,parentN.data.TreePart);
		if (growUpRes.ShitNum > PlayerData.Instance.ShitNum) {
			TipsView.ShowTips("缺少资源，请点左上角等一回合让资源产出或者去其他地方生长");
			return;
		}else if (growUpRes.SunNum > PlayerData.Instance.SunNum) {
            TipsView.ShowTips("缺少资源，请点左上角等一回合让资源产出或者去其他地方生长");
            return;
		}
			
		if (parentN != null) {
			playCostAnim (-(int)growUpRes.SunNum);
			playCostAnim (-(int)growUpRes.ShitNum);
		}


		parentNode.creatNodeGuideTween (this, false);
		var gameRes = PlayerData.Instance.GetResCost (data, parentNode.data.TreePart);
		PlayerData.Instance.SetGrowUpPos (data, parentNode.data.TreePart);

		removeGuide ();
		this.creatNodeResult ();
	}

	public void OnPointerEnter(PointerEventData eventData)
	{
		buttonMask = UIManager.getInstance ().addEffectByPath ("checkin", this, 64, 64);
		buttonMask.setPostion (-32,-32);
	}

	public void playOutputAnim(float num)
	{
		if (num == 0)
			return;

		var go = Instantiate (Resources.Load("ResTips")) as GameObject;
		go.transform.parent = transform;
		go.transform.localPosition = new Vector3 (0, 0, 0);
		go.transform.localScale = new Vector3 (1, 1, 1);
		go.GetComponent<ResTipsView> ().Init ((int)num, cacheLastType != GridType.Air);
		go.SetActive (true);
	}

	public void playCostAnim(float num)
	{
		if (num == 0)
			return;

		var go = Instantiate (Resources.Load("ResTips")) as GameObject;
		go.transform.parent = transform;
		go.transform.localPosition = new Vector3 (0, 0, 0);
		go.transform.localScale = new Vector3 (1, 1, 1);
		go.GetComponent<ResTipsView> ().Init ((int)num, cacheLastType != GridType.Air);
		go.SetActive (true);

	}

	public void OnPointerExit(PointerEventData eventData)
	{
		if (buttonMask != null)
			Destroy (buttonMask.gameObject);
	}
		
	public override string path ()
	{
		return "UIDialog/UIGrid";
	}
}
